<template>
  <view class="template-ranking tn-safe-area-inset-bottom">
    <!-- 组件对应可选项容器 -->
    <view class="rank-list-wrap" 
    :style="{
      paddingTop: vuex_status_bar_height +'px'
    }"
    >
      <view class="tabs-cover">
        <tn-swiper mode="none" :height="160" :list="banners"></tn-swiper>
      </view>
	  <view class="tags-tab">
		<tn-tabs 
			:list="tags" 
			:current="currentTag" 
			name="name" 
			@change="changeTag">
		</tn-tabs>
	  </view>
      <view class="tab-bars" style="margin: 0 30rpx;
      background-color: #fff;z-index: 99;">
        <view class="filters-wrap">
          <view class="search-result">
            <view class="search-scroll-warp">
              <view class="sticky-content">
				<tn-collapse :headStyle="{padding: 0}" :bodyStyle="{padding: 0}" class="filter-collapse">
				  <tn-collapse-item ref="tncollapse" >
					<view slot="default" class="collapse-item-content">
						<tn-list-view :customTitle="true" unlined="all">
							<block v-for="(item, index) in orders" :key="index">
							  <tn-list-cell @click="changeOrderType(item)" :arrow="true">{{item.orderName}}</tn-list-cell>
							</block>
						</tn-list-view>
					</view>
					<view slot="title-all">
						<view class="filter-btn-wrap">
							<view class="ranktype">
							  <text class="tn-icon-filter"></text>
							  {{rankOrderName}}
							  <text class="tn-icon-down-triangle"></text>
							</view>
						</view>	  
					</view>
				  </tn-collapse-item>
				</tn-collapse>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
	<view v-if="iniloading" class="iniloading-wrap">
		<tn-loading mode="circle" :size="100" :show="true"></tn-loading>
	</view>
    <scroll-view scroll-y="true"
      :scroll-anchoring="true" 
      :refresher-threshold="100"
      :refresher-enabled="true"
      :enable-back-to-top="true"
      :refresher-triggered="triggered"
       @refresherrefresh="refreshList" 
       @refresherrestore="onRestore" 
      scroll-with-animation
      class="classics-scroll" 
      @scrolltolower="getList()"
    >
      <block v-for="(item,index) in list" :key="index">
        <view class="rank-item tn-flex tn-flex-row-between tn-flex-col-center">
          <view class="justify-content-item" >
            <view class="tn-flex tn-flex-row-start tn-flex-col-center">
              <view class="tn-flex tn-flex-row-center tn-flex-col-center">
                <view class="avatar-all" @click="gotoDetail(item)">
                  <view class="tn-shadow-blur rank-cover" 
                  :style="'background-image:url('+ item.cover + ');width: 152rpx;height: 152rpx;background-size: cover;'">
					<tn-button class="go-detail-btn" width="100%" 
						@click="gotoDetail(item)" 
						backgroundColor="rgba(138, 91, 241, 0.9)" fontColor="#fff">查看评价</tn-button>
                  </view>
                </view>
                <view class="tn-padding-right tn-padding-left">
                  <view class="tn-padding-right 
                  rank-name
                  max-width-120
                   tn-text-bold tn-text-lg">{{ item.name }}</view>
				 <view class="rank-item-infos">
					 <view class="rank-location">
					   <text class="xicon-location location-icon"></text>
					   <text class="rank-location-title">{{ formatDistance(item.distance) }}</text>
					 </view>
					 <view class="rank-location">
					   <tn-button @click="toLocation(item)" size="sm" backgroundColor="rgba(197, 91, 241, 0.9)" fontColor="#fff">查看地址</tn-button>
					 </view>
				 </view>
                  
                  <view class="tn-flex tn-flex-row-top 
                  tn-flex-col-center rank-action">
                    <view
					 v-for="(label, index) in item.tags"
					 class="label-icon-text tn-flex
					 tn-flex-row-center
                     tn-flex-col-center tn-margin-right-sm"
					 :class="`label-tag-${index%4}`"
					 >
                      <text>{{label}}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="justify-content-item tn-flex 
          tn-flex-direction-column
          tn-flex-column tn-flex-nowrap 
          tn-flex-row-center">
            <text @touchstart="addScore(item)" 
			class="xicon-praise 
            icon-ranking"
			:class="favorites.indexOf(item.id) === -1 ? 'tn-color-grey' : 'tn-color-red'"
			></text>
            <text class="tn-text-xl tn-score-text">{{ item.like_user_count }}</text>
          </view>
        </view>
      </block> 
    </scroll-view>
    <!-- picker -->
    <tn-picker
      v-model="showRegionPicker"
      mode="region"
      :params="{
        city: true,
        area: true,
        province: true
      }"
      :defaultRegin="defaultRegion"
      :areaCode="areaCode"
      :maskCloseable="true"
      @cancel="cancelPicker"
      @confirm="confirmPicker"
    >
    </tn-picker>
  </view>
</template>

<script>
  import {
    getRestaurants, toggleFavorite, getWXConfig
  } from '@/libs/js/restaurant.js'
   import wx from '@/node_modules/jweixin-module/lib/index';
  import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
  const dayjs = require('@/node_modules/dayjs/dayjs.min.js');
  const relativeTime = require("@/node_modules/dayjs/plugin/relativeTime");
  require('@/node_modules/dayjs/locale/zh-cn.js');
  dayjs.locale('zh-cn')
  dayjs.extend(relativeTime);
  export default {
    name: 'TemplateRanking',
    mixins: [template_page_mixin],
    data(){
      return {
        clickId: 'tab1', //点击选项的id
        currentTag: 0,
		favorites: [],
        rankIndex: 1,
		collapseOpen: false,
		rankOrderName: "按点赞排行",
		iniloading: true,
		orders: [
			{
				orderType: 1,
				orderName: "按点赞排行"
			},
			{
				orderType: 2,
				orderName: "按距离排行"
			},
		],
		tags: [],
        banners: [{
			title: '成都美食',
			image: 'https://longcdn.hiotk.com/dinner/20240615112311.jpg'
		}],
        defaultRegion: ['四川省','成都市','双流区'],
        areaCode: [],
        listQuery: {
          limit: 20,
          page: 1,
		  order: 1
        },
        triggered: false,
        showRegionPicker: false,
        loading: false,
        loaded: false,
        list: [],
      }
    },
    created() {
    },
    mounted() {
      this.initPage();
	  
    },
    methods: {
      initPage(x){
		this.favorites = uni.getStorageSync('favorites') || [];
		getWXConfig({
			href: window.location.href
		}).then(res => {
			console.log(res);
			wx.config({
				appId: res.data.appid,
				timestamp: res.data.timestamp,
				nonceStr: res.data.noncestr,
				signature: res.data.signature,
				jsApiList: [
					'updateAppMessageShareData',
					'updateTimelineShareData',
					'onMenuShareTimeline',
					'onMenuShareAppMessage',
					'onMenuShareWeibo',
					'onMenuShareQZone',
					'getLocation',
					'openLocation'
				] //
			})
			const that = this;
			console.log('getLocation')
			wx.getLocation({
			  type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
			  success: function (res) {
				console.log(res)
				var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
				var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
				var speed = res.speed; // 速度，以米/每秒计
				var accuracy = res.accuracy; // 位置精度
				that.listQuery.lng = res.longitude;
				that.listQuery.lat = res.latitude;
				that.getList();
			  },
			  fail: function(res) {
				  that.getList();
			  }
			});
			setTimeout(() => {
				this.iniloading = false;
			}, 3000)
			wx.ready(function(){
				wx.onMenuShareTimeline({
					title: '成都美食排行，只收录十年以上老店', // 分享标题
					link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
					imgUrl: 'https://longcdn.hiotk.com/dinner/20240615163632.jpg',
					success: function () {
					// 用户点击了分享后执行的回调函数
					}
				})
				wx.onMenuShareAppMessage({
					title: '成都美食排行', // 分享标题
					desc: '只收录十年以上老店', // 分享描述
					link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
					imgUrl: 'https://longcdn.hiotk.com/dinner/20240615163632.jpg', // 分享图标
					type: 'link', // 分享类型,music、video或link，不填默认为link
					success: function () {
					// 用户点击了分享后执行的回调函数
					}
				});      
			});
		
		})
       
      },
	  gotoDetail(item){
		  window.location.href = item.link;
	  },
	  changeTag(i) {
		this.loaded = false;
		this.listQuery.tag = this.tags[i].name;
		this.currentTag = i;
		this.listQuery.page = 1;
		this.getList();
	  },
	  toLocation(i) {
		  console.log(i);
		  wx.openLocation({
		    latitude: i.location.coordinates[1], // 纬度，浮点数，范围为90 ~ -90
		    longitude: i.location.coordinates[0], // 经度，浮点数，范围为180 ~ -180。
		    name: i.name, // 位置名
		    address: i.name, // 地址详情说明
		    scale: 16, // 地图缩放级别,整型值,范围从1~28。默认为最大
		    infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
		  });
	  },
      // 跳转
      tn(e) {
        uni.navigateTo({
          url: e,
        });
      },
      addScore(item) {
		this.favorites = uni.getStorageSync('favorites');
		if(!this.favorites){
			this.favorites = [];
		}
		console.log(this.favorites)
		let favorite = '1'
		if(this.favorites && this.favorites.indexOf(item.id) != -1){
			favorite = '2'
		}
        toggleFavorite({
          restaurantsId: item.id,
		  favorite
        }).then(res => {
          if(res.status == 'success'){
			  if(favorite === '2'){
				item.like_user_count -= 1;
				this.favorites.splice(this.favorites.indexOf(item.id), 1)
				uni.setStorageSync('favorites', this.favorites);
			  }else{
				this.favorites.push(item.id)
				item.like_user_count += 1;
				uni.setStorageSync('favorites', this.favorites);
			  }
          }else{
            this.$t.message.toast(res.info);
          }
        })
      },
      onRestore() {
        this.triggered = false; 
      },
      refreshList() {
        if (this.loading) return;
        this.loaded = false;
        this.triggered = true;
        console.log('refresh')
        this.listQuery.page = 1;
        this.getList();
        setTimeout(() => {
          this.triggered = false;
        }, 3000)
      },
      getList(){
        console.log(this.listQuery)
        if(this.loading || this.loaded){
          return;
        }
        console.log('getList')
        this.loading = true;
        getRestaurants(this.listQuery).then(res => {
			this.triggered = false;
        	if (res.status === 'success') {
        		const t = res.data.rows
				if(this.listQuery.page == 1){
				  this.list = t;
				}else{
				  this.list = this.list.concat(t);
				}
					
				if(this.tags.length == 0){
					this.tags = res.data.tags;
				}
				
				if(t.length < this.listQuery.limit){
				  this.loaded = true;
				}
			}else{
				this.loaded = true;
			}
			this.listQuery.page++;
			this.loading = false;
			this.iniloading = false;
        })
      },
      // 点击取消按钮
      cancelPicker(event) {
        this.$t.message.toast('点击了取消按钮')
      },
	  changeOrderType(item) {
		this.rankOrderName = item.orderName;
		this.listQuery.order = item.orderType;
		this.collapseOpen = false;
		this.listQuery.page = 1;
		this.$refs.tncollapse.manualClose();
		this.getList();
	  },
      // 点击确认按钮
      confirmPicker(event) {
        console.log(event);
        this.defaultRegion = [event.province.label, event.city.label, event.area.label];
      },
      getCount(c) {
        if(this.$t.number.isNumber(c)){
          if(c > 10000){
            return (c / 10000).toFixed(2) + '万'
          }
          return c;
        }else{
          return 0;
        }
      },
      // 更新轮播容器信息
      formatDistance(distance){
        if(distance> 1000){
          return (distance / 1000).toFixed(1) + 'km'
        }else{
          return Math.floor(distance) + 'm'; 
        }
      },
	  formatAge(time){
		return  dayjs(time).toNow(true)
	  },
      // 打开Picker
      openRegionPicker() {
        this.showRegionPicker = true
      },
    }
  }
</script>

<style lang="scss" scoped>
  /* 背景*/
  .template-ranking {
    margin: 0;
    width: 100%;
    height: 100vh;
    overflow: hidden;
  }
  .tn-score-text{
    text-align: center;
    margin-top: 10rpx;
    font-size: 18px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    color: #262626;
  }
  .tabs-cover{
    padding: 32rpx;
  }
  .iniloading-wrap{
	  width: 100%;
	  display: flex;
	  margin-top: 100rpx;
	  height: calc(100vh - 400rpx);
	  align-items: flex-start;
	  justify-content: center;
  }
  /* 胶囊*/
  .tn-custom-nav-bar__back {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.15);
    border-radius: 1000rpx;
    border: 1rpx solid rgba(255, 255, 255, 0.5);
    color: #FFFFFF;
    font-size: 18px;
    
    .icon {
      display: block;
      flex: 1;
      margin: auto;
      text-align: center;
    }
    
    &:before {
      content: " ";
      width: 1rpx;
      height: 110%;
      position: absolute;
      top: 22.5%;
      left: 0;
      right: 0;
      margin: auto;
      transform: scale(0.5);
      transform-origin: 0 0;
      pointer-events: none;
      box-sizing: border-box;
      opacity: 0.7;
      background-color: #FFFFFF;
    }
  }
  .classics-scroll{
    height: calc(100vh - 400rpx);
    background: #F6F6F6;
    box-sizing: border-box;
    .rank-item{
      background-color: #fff;
      padding: 30rpx;
    }
    .rank-item:last-child{
      margin-bottom: 100rpx;
    }
    .rank-item + .rank-item{
      margin-top: 16rpx;
    }
  }
  
  /* 标题 start */
  .nav_title {
    -webkit-background-clip: text;
    color: transparent;
    
    &--wrap {
      position: relative;
      display: flex;
      height: 120rpx;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      background-image: url(https://fastcdn.hidino.com/hiotk/title44.png);
      background-size: cover;
    }
  }
  /* 标题 end */
  
  /* 图标 start */
  .icon-ranking {
    font-variant: small-caps;
    line-height: 60rpx;
    margin-top: 10rpx;
    display: inline-flex;
    text-align: center;
    justify-content: center;
    vertical-align: middle;
    font-size: 60rpx;
    color: #fff;
    padding: 0;
    white-space: nowrap;
    background-size: cover;
    background-position: 50%;
    border-radius: 5000rpx;  
  }
  
  
/* 用户信息 start */
  .user-info {
    &__container {
      margin-top: -10vh;
    }
    
    &__avatar-one {
      margin-top: -90rpx;
      width: 180rpx;
      height: 180rpx;
      border: 8rpx solid rgba(255,255,255,0.05);
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
    }
    &__avatar-two {
      width: 140rpx;
      height: 140rpx;
      border: 8rpx solid rgba(255,255,255,0.05);
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
    }
    &__avatar-three {
      margin-top: 60rpx;
      width: 120rpx;
      height: 120rpx;
      border: 8rpx solid rgba(255,255,255,0.05);
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
    }
    
    &__nick-name-one {
      width: 180rpx;
      color: #000;
      margin-top: 26rpx;
      font-size: 26rpx;
      font-weight: 600;
      text-align: center;
    }
    &__nick-name-two {
      width: 140rpx;
      color: #000;
      margin-top: 26rpx;
      font-size: 24rpx;
      font-weight: 600;
      text-align: center;
    }
    &__nick-name-three {
      width: 120rpx;
      color: #000;
      margin-top: 26rpx;
      font-size: 24rpx;
      font-weight: 600;
      text-align: center;
    }
    &__nick-number-one {
      width: 180rpx;
      color: #000;
      margin-top: 13rpx;
      font-size: 26rpx;
      font-weight: 600;
      text-align: center;
    }
    &__nick-number-two {
      width: 140rpx;
      color: #000;
      margin-top: 13rpx;
      font-size: 24rpx;
      font-weight: 600;
      text-align: center;
    }
    &__nick-number-three {
      width: 120rpx;
      color: #000;
      margin-top: 13rpx;
      font-size: 24rpx;
      font-weight: 600;
      text-align: center;
    }
  }
  .avatar-all {
    position: relative;
    .rank-badge{
      position: absolute;
      left: 0;
      top: 0;
      width: 60rpx;
      height: 86rpx;
      z-index: 2;
    }
    .rank-cover{
      width: 152rpx;
      height: 152rpx;
	  position: relative;
	  .go-detail-btn{
		position: absolute;
		width: 100%;
		border-radius: 0;
		white-space: nowrap;
		bottom: 0;
		left: 0;
	  }
    }
  }
  /* 用户信息 end */
  
  .rank-name{
    font-size: 16px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    color: #262626;
    line-height: 22px;
  }
  .rank-action{
    margin-top: 10px;
    .label-icon-text{
      padding: 0px 10px;
      height: 18px;
      font-size: 14px;
      font-family: PingFang SC, PingFang SC;
      font-weight: bold;
      text-align: center;
	  color: #FFFFFF;
	  border-radius: 2px;
	  &.label-tag-0{
	    background-color: rgba(236, 84, 70, 0.9);
	  }
	  &.label-tag-1{
	    background-color: rgba(244, 164, 49, 0.9);
	  }
	  &.label-tag-2{
	    background-color: rgba(138, 91, 241, 0.9);
	  }
	  &.label-tag-3{
	    background-color: rgba(197, 91, 241, 0.9);
	  }
    }
	
  }
  .rank-item-infos{
	  display: flex;
	  flex-direction: row;
	  align-items: center;
	  justify-content: flex-start;
  }
  .rank-location{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    font-size: 16px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    margin-top: 5px;
    color: #999999;
	margin-right: 4px;
    .location-icon{
      font-size: 28rpx;
      margin: 0 8rpx 0 0rpx;
    }
	.tn-icon-history{
		color: #999999;
		font-size: 32rpx;
		margin: 0 8rpx 0 0rpx;
	}
    .rank-address{
      
    }
  }
  /* 文字截取*/
  .clamp-text-1 {
    -webkit-line-clamp: 1;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .clamp-text-2 {
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  /* 顶部背景图 start */
  .top-background {
    width: 100%;
    height: 200px;
    background: linear-gradient(91deg, #FDA864 0%, #FE5D55 100%);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    margin-bottom: -30px;
  }
  /* 顶部背景图 end */
  
  .tab-bars{
    z-index: 999;
    background-color: #ffffff;
  }
  
  .max-width-120{
    width: 380rpx;
  }

  /* 底部 start*/
  
  .tabbar {
    align-items: center;
    min-height: 130rpx;
  	padding: 0;
  	height: calc(130rpx + env(safe-area-inset-bottom) / 2);
  	padding-bottom: calc(30rpx + env(safe-area-inset-bottom) / 2);
    padding-left: 10rpx;
    padding-right: 10rpx;
  }
  
    /* 毛玻璃*/
  .dd-glass {
     width: 100%;
     backdrop-filter: blur(20rpx);
    -webkit-backdrop-filter: blur(20rpx);
  }
  
</style>
<style lang="scss">
  .filter-cate-btns{
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 0px;
    flex-direction: row;
    column-gap: 10px;
    margin-bottom: 20rpx;
    .filter-cate-btn{
      display: flex;
      flex: 1 1 0;
      align-items: center;
      background: #F2F2F2;
      height: 60rpx;
      border-radius: 4px 4px 4px 4px;
      z-index: 1;
      justify-content: center;
      position: relative;
      .filter-cate-bg{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: inherit;
        z-index: -1;
        opacity: 0;
        transform: scale(0);
        transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      }
      .filter-cate-text{
        width: 84rpx;
        height: 40rpx;
        white-space: nowrap;
        font-size: 14px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #666666;;
        text-align: center;
        transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        line-height: 40rpx;
      }
      &.active{
        .filter-cate-bg{
          opacity: 1;
          transform: scale(1);
          background: linear-gradient(180deg, #FF7E45 0%, #EC5446 100%);
        }
        .filter-cate-text{
          color: #ffffff;
        }
      }
    }
  }
.rank-list-wrap{
    position: sticky;
    top: 0;
}
  .filter-collapse{
  	width: 100%;
  	.tn-collapse-item__body{
  		.tn-collapse-item__body__content{
  			padding-left: 0;
  		}
  	}
  }
  .search-result {
		width: 100%;
		display: flex;
		flex-direction: column;
		.search-scroll-warp {
			flex: 1;
			background-color: #fff;
			
			.sticky-content {
				display: flex;
				justify-content: space-between;
				padding: 20rpx 0rpx 10rpx 0;
				position: relative;
				
				.ranktype{
				  height: 60rpx;
				  background: #F2F2F2;
				  border-radius: 4px 4px 4px 4px;
				  padding: 8rpx 12rpx;
				  text-align: center;
				  display: flex;
				  align-items: center;
				  flex-direction: row;
				  opacity: 1;
				  font-size: 14px;
				  font-family: PingFang SC, PingFang SC;
				  font-weight: 400;
				  white-space: nowrap;
				  color: #666666;
				}
				.location {
					height: 60rpx;
					background: #F2F2F2;
					border-radius: 4px 4px 4px 4px;
					padding: 8rpx 12rpx;
					text-align: center;
					display: flex;
					align-items: center;
					flex-direction: row;
					opacity: 1;
					white-space: nowrap;
					font-size: 14px;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					color: #666666;
				}


				.sort-select {
					color: #000;
					font-weight: blod;
					font-size: 32rpx;

					.sort-list {
						padding: 24rpx 48rpx;
						display: flex;
						flex-direction: column;
						gap: 16rpx;

						.sort-item {
							font-size: 24rpx;
							display: flex;
							justify-content: space-between;

							&.selected {
								font-size: 28rpx;
								font-weight: bold;
							}

							.icon-choose {
								color: #0091ff;
							}
						}
					}
				}

				.condition-filter {
					color: #666;
				}
			}
		}

		.content-warp {
			padding: 24rpx 48rpx;
		}
	}
</style>